<template>
    <div class="change-password-container">
        <h2>修改密码</h2>
        <div class="password-form">
            <div class="form-group">
                <label>当前密码</label>
                <input type="password" v-model="currentPassword" @blur="validateCurrentPassword" placeholder="请输入当前密码">
            </div>
            <div class="form-group">
                <label>新密码</label>
                <input type="password" v-model="newPassword" placeholder="请输入新密码">
            </div>
            <div class="form-group">
                <label>确认新密码</label>
                <input type="password" v-model="confirmPassword" placeholder="请再次输入新密码">
            </div>
            <div class="password-rules">
                <p>密码要求：</p>
                <ul>
                    <li>长度至少为6位</li>
                    <li>仅包含数字</li>
                    <li>不能与旧密码相同</li>
                </ul>
            </div>
            <div class="form-actions">
                <button @click="resetForm">重置</button>
                <button class="primary" @click="changePassword" :disabled="loading">{{ loading ? '处理中...' : '确认修改'
                    }}</button>
            </div>
        </div>
    </div>
</template>

<script>
import md5 from 'md5'

export default {
    name: 'ChangePassword',
    data() {
        return {
            currentPassword: '',
            newPassword: '',
            confirmPassword: '',
            loading: false,
        }
    },
    methods: {
        async validateCurrentPassword() {
            try {
                const res = await this.$axios({
                    method: 'post',
                    url: 'http://localhost:8085/BankManage/bank/confirmPassword',  // 使用完整URL
                    data: {
                        cardno: this.$store.state.userInfo.cardno,
                        password: md5(this.currentPassword)
                    }
                });

                if (res.data.code != 0) {
                    this.$message.error('当前密码不正确');
                }
            } catch (error) {
                console.error('验证当前密码时出错:', error);
                this.$message.error('验证密码时发生错误');
            } finally {
                this.loading = false; // 无论成功失败都关闭加载状态
            }
        },
        validatePassword() {
            if (!this.newPassword) {
                this.$message.warning('请输入新密码')
                return;
            }

            if (!/^\d{6,}$/.test(this.newPassword)) {
                this.$message.warning('新密码必须至少为6位数字')
                return;
            }

            if (this.newPassword === this.currentPassword) {
                this.$message.warning('不能修改原密码')
                return;
            }

            if (this.confirmPassword) {
                if (this.newPassword !== this.confirmPassword) {
                    this.$message.warning('新密码和确认密码不一致');
                    return;
                }
            }
        },
        changePassword() {
            try {
                // 先验证当前密码是否正确
                this.$axios({
                    method: 'get',
                    url: 'http://localhost:8085/BankManage/bank/confirmPassword',
                    params: {
                        cardno: this.$store.state.userInfo.cardno,
                        password: md5(this.currentPassword)
                    },
                    timeout: 10000,  // 增加超时时间到10秒
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => {
                        if (response.data && response.data.code === 0) {
                            this.$message.error("当前密码不正确");
                        }
                    });
                if (!this.validatePassword()) {
                    return;
                }
                this.loading = true;
                // 先验证当前密码是否正确
                this.$axios({
                    method: 'get',
                    url: 'http://localhost:8085/BankManage/bank/confirmPassword',
                    params: {
                        cardno: this.$store.state.userInfo.cardno,
                        password: md5(this.confirmPassword)
                    },
                    timeout: 10000,  // 增加超时时间到10秒
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => {
                        if (response.data.code === 0) {
                            this.$message.success("密码修改成功，请重新登录");
                            this.resetForm();
                            // 清除用户状态
                            this.$store.commit('clearUserInfo');
                            // 延迟跳转到登录页面
                            setTimeout(() => {
                                this.$router.push('/');
                            }, 1500);
                        } else {
                            this.errorMessage = response.data.message || '密码修改失败';
                        }
                    });
            } catch (error) {
                console.error('修改密码时出错:', error);
                this.$message.error("服务器错误，请稍后重试");
            } finally {
                this.loading = false;
            }
        },
        resetForm() {
            this.currentPassword = '';
            this.newPassword = '';
            this.confirmPassword = '';
        }
    }
}
</script>

<style scoped>
.change-password-container {
    max-width: 500px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
    text-align: center;
    color: #333;
    margin-bottom: 30px;
}

.password-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

label {
    font-weight: bold;
    color: #333;
}

input {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

input:focus {
    outline: none;
    border-color: #409EFF;
}

.password-rules {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    font-size: 14px;
}

.password-rules p {
    margin: 0 0 10px 0;
    font-weight: bold;
}

.password-rules ul {
    margin: 0;
    padding-left: 20px;
}

.password-rules li {
    margin-bottom: 5px;
    color: #666;
}

.form-actions {
    display: flex;
    gap: 15px;
    justify-content: flex-end;
    margin-top: 20px;
}

button {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

button:not(.primary) {
    background-color: #f5f7fa;
    color: #606266;
}

button:not(.primary):hover {
    background-color: #e6e8eb;
}

button.primary {
    background-color: #409EFF;
    color: white;
}

button.primary:hover {
    background-color: #66b1ff;
}

button:disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
}

.error-message {
    color: #f56c6c;
    font-size: 14px;
    text-align: center;
    padding: 10px;
    background-color: #fef0f0;
    border-radius: 4px;
}

.success-message {
    color: #67c23a;
    font-size: 14px;
    text-align: center;
    padding: 10px;
    background-color: #f0f9eb;
    border-radius: 4px;
}
</style>
<div v-if="newPasswordError" class="error-message">{{ newPasswordError }}</div>
<div v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</div>